#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <fstream>
#include <algorithm>
using namespace std;

void menu()
{
	cout << "   运动会成绩管理        " << endl;
	cout << "=====================  " << endl;
	cout << "1．录入项目成绩信息       " << endl;
	cout << "2．统计学校积分          " << endl;
	cout << "3．查询学校积分          " << endl;
	cout << "4．查询学校项目信息       " << endl;
	cout << "5．按学校总积分排序       " << endl;
	cout << "6．查询项目信息          " << endl;
	cout << "7．查询获奖项目最多的学校  " << endl;
	cout << "8．项目信息保存          " << endl;
	cout << "请选择（1 - 8，0：退出）：" << endl;
	cout << "=====================" << endl;
}

struct Project {
	int projectID;
	string projectName;
	vector<pair<int, int>> results; // pair<rank, schoolID>
	bool topFive;
	int getScore(int rank) const {
		vector<int> topFiveScores = { 7, 5, 3, 2, 1 };
		vector<int> topThreeScores = { 5, 3, 2 };
		if (topFive) {
			return rank <= 5 ? topFiveScores[rank - 1] : 0;
		}
		else {
			return rank <= 3 ? topThreeScores[rank - 1] : 0;
		}
	}
};

struct School {
	int schoolID;
	string schoolName;
	int totalScore;
	int maleScore;
	int femaleScore;
	int awardCount;
	School() : totalScore(0), maleScore(0), femaleScore(0), awardCount(0) 
	{}
	School(int SchoolId,string Schoolname)
		:schoolID(SchoolId),schoolName(Schoolname)
	{}
};

class SportsMeetingManager {
public:
	SportsMeetingManager(string& filename)
		:_filename(filename)
	{
	}
	~SportsMeetingManager()=default;
	void addSchool(int schoolID, const string& schoolName) {
		_schools.emplace(schoolID, School(schoolID, schoolName));
	}
	void LoadProjectsFromFile()//加载文件
	{
		ifstream inFile(_filename);
		if (!inFile) {
			cerr << "无法打开文件\n";
			return;
		}
		Project project;
		while (inFile >> project.projectID >> project.projectName >> project.topFive) {//输入进文件
			int rank, schoolID;
			project.results.clear();//清空 便于不停的输入 减少重复的创建
			while (inFile >> rank >> schoolID) {
				if (rank == -1) break;
				project.results.push_back({ rank, schoolID });
			}
			_projects.push_back(project);
		}
		inFile.close();
	}
	void SaveProjectsToFile()//保存进文件
	{
		ofstream outFile(_filename);
		if (!outFile) {
			cerr << "无法打开文件\n";
			return;
		}

		for (const auto& project : _projects) {
			outFile << project.projectID << " " << project.projectName << " " << project.topFive << "\n";
			for (const auto& result : project.results) {
				outFile << result.first << " " << result.second << "\n";//输出进文件
			}
			outFile << "-1\n";
		}
		outFile.close();
	}
	void InputProjectResults()
	{
		Project project;
		cout << "输入项目编号：";
		cin >> project.projectID;
		cout << "输入项目名称：";
		cin >> project.projectName;
		cout << "该项目是否取前五名积分(1:是, 0:否): ";
		cin >> project.topFive;

		int rank, schoolID;
		while (true) {
			cout << "输入排名和学校编号（输入-1结束）：";
			cin >> rank;
			if (rank == -1) break;
			cin >> schoolID;
			project.results.push_back({ rank, schoolID });
		}
		_projects.push_back(project);
	}
	void CalculateScores()
	{
		for (auto& entry : _schools) {
			entry.second.totalScore = 0;
			entry.second.maleScore = 0;
			entry.second.femaleScore = 0;
			entry.second.awardCount = 0;
		}

		// 计算新的积分信息
		for (const auto& project : _projects) {
			for (const auto& result : project.results) {
				int rank = result.first;
				int schoolID = result.second;
				int score = project.getScore(rank);
				_schools[schoolID].totalScore += score;
				if (project.projectID <= _projects.size() / 2) {
					_schools[schoolID].maleScore += score;
				}
				else {
					_schools[schoolID].femaleScore += score;
				}
				if (rank <= (project.topFive) ? 5 : 3) {
					_schools[schoolID].awardCount++;
				}
			}
		}
	}
	void QuerySchoolScores(int schoolID) const
	{
		if (_schools.find(schoolID) != _schools.end()) {
			School school = _schools.at(schoolID);
			cout << "学校名称: " << school.schoolName << "\n";
			cout << "总积分: " << school.totalScore << "\n";
			cout << "男子项目积分: " << school.maleScore << "\n";
			cout << "女子项目积分: " << school.femaleScore << "\n";
		}
		else {
			cout << "没有找到该学校的信息。\n";
		}
	}
	void QuerySchoolProjects(int schoolID) const
	{
		if (_schools.find(schoolID) != _schools.end()) {
			School school =_schools.at(schoolID);
			cout << "学校名称: " << school.schoolName << "\n";
			cout << "获奖项目信息:\n";
			for (const auto& project : _projects) {
				for (const auto& result : project.results) {
					if (result.second == schoolID) {//找到了
						cout << "项目名称: " << project.projectName
							<< " 排名: " << result.first
							<< " 积分: " << project.getScore(result.first) << "\n";
					}
				}
			}
		}
		else {
			cout << "没有找到该学校的信息。\n";
		}
	}
	void SortSchoolsByTotalScore() const
	{
		vector<School> schoolList;//排序表 
		for (const auto& entry : _schools) {
			schoolList.push_back(entry.second);
		}

		sort(schoolList.begin(), schoolList.end(), [](const School& a, const School& b) {//lamda排序

			return a.totalScore > b.totalScore;
			});

		for (const auto& school : schoolList) {
			cout << "学校名称: " << school.schoolName << " 总积分: " << school.totalScore << "\n";
		}
	}
	void QueryProjectInfo(int projectID) const
	{
		for (const auto& project : _projects) {
			if (project.projectID == projectID) {
				cout << "项目名称: " << project.projectName << "\n";
				for (const auto& result : project.results) {
					int schoolID = result.second;
					cout << "排名: " << result.first
						<< " 学校名称: " << _schools.at(schoolID).schoolName
						<< " 积分: " << project.getScore(result.first) << "\n";
				}
				return;
			}
		}
		cout << "没有找到该项目的信息。\n";
	}
	void QuerySchoolWithMostAwards() const
	{
		const School* maxAwardSchool = nullptr;
		for (const auto& entry :_schools) {
			if (maxAwardSchool == nullptr || entry.second.awardCount > maxAwardSchool->awardCount) {
				maxAwardSchool = &entry.second;
			}
		}
		if (maxAwardSchool) {
			cout << "获奖项目最多的学校: " << maxAwardSchool->schoolName
				<< " 获奖项目数: " << maxAwardSchool->awardCount << "\n";
		}
		else {
			cout << "没有找到获奖项目最多的学校。\n";
		}

	}
private:
	map<int, School> _schools;//用来维护学校
	vector<Project> _projects;//用来维护项目
	const string _filename;//指定的文件
};
